// 登录鉴权
checkLogin()

// 退出登录的逻辑
logout()

getname()

// 添加弹层
const modol = new bootstrap.Modal(document.querySelector('#modal'))

// 添加按钮和修改按钮的标识
let flag
// 渲染学生列表函数
randerStudentList()
async function randerStudentList(data) {

    const res = await axios({ url: '/students' })
    const students = res.data.data.map((item, index) => {
        return `<tr>
                      <td>${item.name}</td>
                      <td>${item.age}</td>
                      <td>${item.gender === 0 ? '男' : '女'}</td>
                      <td>第${item.group}组</td>
                      <td>${item.hope_salary}</td>
                      <td>${item.salary}</td>
                      <td>${item.province}${item.city}${item.area}</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i data-id="${item.id}" class="bi bi-pen"></i></a>
                        <a href="javascript:;" class="text-danger"><i data-id="${item.id}" class="bi bi-trash"></i></a>
                      </td>
                    </tr>`
    })
    document.querySelector('.list').innerHTML = students.join('')
    document.querySelector('.total').innerText = students.length
}
// 删除和修改
document.querySelector('.list').addEventListener('click', async function (e) {
    // 删除
    if (e.target.className === 'bi bi-trash') {
        const id = e.target.dataset.id

        if (confirm('确定要删除吗？')) {
            const res = await axios({
                url: `/students/${id}`,
                method: 'delete'
            })
            randerStudentList()
        }
    }
    // 点击修改回填数据
    if (e.target.className === 'bi bi-pen') {
        // 修复省市区请求越发越多的bug
        document.querySelector('select[name="province"]').removeEventListener('change', handleProvinceChange)
        document.querySelector('select[name="city"]').removeEventListener('change', handleCityChange)
        // 获得id
        const id = e.target.dataset.id
        // 修改标题
        document.querySelector('.modal-title').innerText = '修改学生'
        // 获取省份
        await getprovince()
        // 获取学生数据回填数据
        const { data: { data } } = await axios({
            url: `/students/${id}`,
            method: 'get',
        })
        // 回填数据
        const form = document.querySelector('#form')
        for (let key in data) {
            if (form[key]) {
                form[key].value = data[key]
            }
        }
        // 设置省市和地区的值
        form['province'].value = data.province
        await Promise.all([
            getCity(data.province),
            getArea(data.province, data.city)
        ])
        form['city'].value = data.city
        form['area'].value = data.area
        // 打开弹层
        modol.show()
        flag = true
        // 先移除之前的事件监听器
        document.querySelector('#submit').removeEventListener('click', modifyInformation)
        document.querySelector('#submit').removeEventListener('click', addStudent)
        document.querySelector('#submit').addEventListener('click', modifyInformation)
    }
})
// 获取省份三级联动
async function getprovince() {
    const province = await axios({ url: '/api/province' })
    const provinceList = province.data.list.map(item => { return `<option>${item}</option>` })
    document.querySelector('select[name="province"]').innerHTML = '<option>--省份--</option>' + provinceList.join('')
    // 获取城市，省份改变发起请求获得城市
    document.querySelector('select[name="province"]').addEventListener('change', handleProvinceChange)
}

async function handleProvinceChange(e) {
    const pname = e.target.value
    await getCity(pname)
    // 初始化区的下拉框
    document.querySelector('select[name="area"]').innerHTML = '<option>--地区--</option>'
}

// 获取城市
async function getCity(pname) {
    const { data: { list } } = await axios({ url: `/api/city?pname=${pname}` })
    const cityList = list.map(item => { return `<option>${item}</option>` })
    document.querySelector('select[name="city"]').innerHTML = '<option>--城市--</option>' + cityList.join('')
    // 获取地区，城市改变发起请求获得地区
    document.querySelector('select[name="city"]').addEventListener('change', handleCityChange)
}

async function handleCityChange(e) {
    const cname = e.target.value
    const pname = document.querySelector('select[name="province"]').value
    await getArea(pname, cname)
}

// 获取地区
async function getArea(pname, cname) {
    const { data: { list } } = await axios({
        url: '/api/area',
        params: {
            pname: pname,
            cname: cname
        }
    })
    const areaList = list.map(item => { return `<option>${item}</option>` })
    document.querySelector('select[name="area"]').innerHTML = '<option>--地区--</option>' + areaList.join('')
}

// 添加按钮添加点击事件，打开弹层
document.querySelector('#openModal').addEventListener('click', async function () {
    // 修复省市区请求越发越多的bug
    document.querySelector('select[name="province"]').removeEventListener('change', handleProvinceChange)
    document.querySelector('select[name="city"]').removeEventListener('change', handleCityChange)
    // 打开弹层
    document.querySelector('.modal-title').innerText = '添加学生'
    modol.show()
    // 清零表单
    document.querySelector('#form').reset()
    // 获取省份三级联动
    await getprovince()
    // 初始化城市和地区的下拉框
    document.querySelector('select[name="city"]').innerHTML = '<option>--城市--</option>'
    document.querySelector('select[name="area"]').innerHTML = '<option>--地区--</option>'
    flag = false
    // 先移除之前的事件监听器
    document.querySelector('#submit').removeEventListener('click', modifyInformation)
    document.querySelector('#submit').removeEventListener('click', addStudent)
    document.querySelector('#submit').addEventListener('click', addStudent)
})

// 修改学生信息
async function modifyInformation() {
    const id = document.querySelector('.bi.bi-pen').dataset.id
    const form = document.querySelector('#form')
    const formData = serialize(form, { hash: true, empty: true })
    formData.age = parseInt(formData.age)
    formData.group = parseInt(formData.group)
    formData.hope_salary = parseInt(formData.hope_salary)
    formData.salary = parseInt(formData.salary)
    formData.gender = parseInt(formData.gender)
    const res = await axios({
        url: `/students/${id}`,
        method: 'put',
        data: {
            ...formData
        }
    })
    randerStudentList()
    showTost('修改成功')
    modol.hide()
}

// 添加学生
async function addStudent() {
    const form = document.querySelector('#form')
    const formData = serialize(form, { hash: true, empty: true })
    formData.age = parseInt(formData.age)
    formData.group = parseInt(formData.group)
    formData.hope_salary = parseInt(formData.hope_salary)
    formData.salary = parseInt(formData.salary)
    formData.gender = parseInt(formData.gender)
    const res = await axios({
        url: '/students',
        method: 'post',
        data: {
            ...formData
        }
    })
    randerStudentList()
    showTost('添加成功')
    modol.hide()
}